var graph = new joint.dia.Graph();

var nodes = [];
var lines = [];
 
 
var paper = new joint.dia.Paper({
    el: $('#paper'),
	height: $('#paper').height(),
	width: $('#paper').width(),
    gridSize: 1,
    model: graph,
    perpendicularLinks: true,
    restrictTranslate: true
});

/**
 * 
 */
var splitNameToArray = function(nameStr, slength) {
	var nameArr = [];
	var splitLen = slength ? slength : 5;
	if (nameStr.length > splitLen) {  	
    	name = nameStr.substring(0, splitLen);
    	nameArr.push(name);
    	var twoLineLen = 2 * splitLen;
    	if (nameStr.length > twoLineLen) {
    		nameLine2 = nameStr.substring(splitLen, twoLineLen);
			nameLine3 = nameStr.substring(twoLineLen);	
			nameArr.push(nameLine2);	
			nameArr.push(nameLine3);	
    	} else {
    		nameLine2 = name.substring(splitLen);	
    		nameArr.push(nameLine2);	
    		nameArr.push("");
    	}
    } else {
    	nameArr.push(nameStr);
		nameArr.push("");	
		nameArr.push("");	    	
    }

    return nameArr;
}

var resetCellHeight = function(nameArr, cellObj) {
    if (nameArr[2].length > 0) {
    	cellObj.attributes.size.height = 68;	
    } else if (nameArr[1].length > 0) {
    	cellObj.attributes.size.height = 45;	
    }
}

var member = function(id, x, y, rank, name, image, background, textColor) {
    textColor = textColor || "#000";
    var nameArry = splitNameToArray(name);
	
    var cell = new joint.shapes.org.Member({
        position: { x: x, y: y },
        id: id,
        attrs: {
            '.card': { fill: background, stroke: '#333', "stroke-width":"1"},
              image: { 'xlink:href': 'images/'+ image, "magnet":true, opacity: 0.7 },
            '.rank': { text: rank, fill: textColor, 'word-spacing': '-5px', 'letter-spacing': 0},
            '.name': { text: nameArry[0], fill: textColor, 'font-size': 13, 'font-family': 'Arial', 'letter-spacing': 0 },
			'.name_line2': { text: nameArry[1], fill: textColor, 'font-size': 13, 'font-family': 'Arial', 'letter-spacing': 0 },
			'.name_line3': { text: nameArry[2], fill: textColor, 'font-size': 13, 'font-family': 'Arial', 'letter-spacing': 0 }
        }
    });

    resetCellHeight(nameArry, cell);
	
    graph.addCell(cell);
    return cell;
};

joint.dia.Element.define('Star', {
            markup: [{
                tagName: 'ellipse',
                selector: 'ellipse'
            }],
            size: {
                width: 30,
                height: 30
            },
            attrs: {
                ellipse: {
                    refCX: '50%',
                    refCY: '50%',
                    refRx: '50%',
                    refRy: '50%',
                    fill: 'white',
                    stroke: 'white',
                    strokeOpacity: 0.5,
                    strokeWidth: 8,
                    cursor: 'pointer'
                }
            }
        })


/**
 * 双击， 显示属性
 */
paper.on('cell:pointerdblclick', 
    function(cellView, evt, x, y) {
	    var cellObj = cellView.model;
	    
	    var modelType = cellObj.get("type");
	    
		if (modelType == "org.Member" || modelType == "org.START" || modelType == "org.END" || modelType == "org.GateWay") {
			showNodeView(cellObj, modelType);
			
		} else if (modelType == "fsa.Arrow") {
			showLinkView(cellObj);
		} else if (modelType == "fsa.ArrowNoback") {
			showLinkView(cellObj);
		} 
    }
);


paper.on('link:options', function (cellView, evt, x, y) {   
		debugger;
	var cellObj = cellView.model;	
	var modelType = cellObj.get("type");
	
	if (modelType == "org.Member") {
		showNodeView(cellObj, modelType);
		
	} else if (modelType == "fsa.Arrow") {
		showLinkView(cellObj);
	} else if (modelType == "fsa.ArrowNoback") {
		showLinkView(cellObj);
	} 	
});


paper.on('remove', function(cellView, evt, x, y) { 
		debugger;
	evt.stopPropagation();
	var cellObj = cellView.model;	
	var modelType = cellObj.get("type");
	if (modelType == "org.Member" || modelType == "org.START" || modelType == "org.END" || modelType == "org.GateWay") {
		removeNode(cellObj);
	} else if (modelType == "fsa.Arrow") {
		removeLink(cellObj);
	} else if (modelType == "fsa.ArrowNoback") {
		removeLink(cellObj);
	} 	
});

paper.on('tool:remove', function(cellView, evt, x, y) { 
		debugger;
	evt.stopPropagation();
	var cellObj = cellView.model;	
	var modelType = cellObj.get("type");
	if (modelType == "org.Member") {
		removeNode(cellObj);
	} else if (modelType == "fsa.Arrow") {
		removeLink(cellObj);
	} else if (modelType == "fsa.ArrowNoback") {
		removeLink(cellObj);
	} 	
});



/**
 * 右键， 删除
 */
paper.on('cell:contextmenu', 
    function(cellView, evt, x, y) { 
		var modelType = cellView.model.attributes.type;
		if (modelType == "org.Member") {  //节点
	        //显示节点，属性
			
			var objId = cellView.model.id;
			removeNode(cellView.model);
		} else if (modelType == "fsa.Arrow" || modelType == "fsa.ArrowNoback") { //线
			//显示线属性
			
			removeLink(cellView.model);
		}
    }
);

function link(source, target, label, vertices, linkId) {
    var connAttr = {};
	if (label && label.length > 0) {
		connAttr = {
            '.connection': { "stroke-dasharray":"4 2"}
		};
	}
    var cell = new joint.shapes.fsa.Arrow({
        source: { id: source.id },
        target: { id: target.id },
        id: linkId,
        labels: [{ position: .5, attrs: { text: { text: label || '', 'font-weight': 'bold' } } }],
        attrs: connAttr,		
        vertices: vertices || []
    });
    graph.addCell(cell);
    return cell;
}

function linkNoBack(source, target, label, vertices, linkId) {
    var connAttr = {};
	if (label && label.length > 0) {
		connAttr = {
            '.connection': { "stroke-dasharray":"4 2"}
		};
	}	
    var cell = new joint.shapes.fsa.ArrowNoback({
        source: { id: source.id },
        target: { id: target.id },
        id: linkId,
        labels: [{ position: .5, attrs: { text: { text: label || '', 'font-weight': 'bold' } } }],
		attrs: connAttr,
        vertices: vertices || []
    });
    graph.addCell(cell);
    return cell;
}

function showNodeView(cellObj, modelType) {

	var cellObjId = cellObj.id;
	var nodeName = cellObj.get("attrs")[".name"].text;


    var $textAndPic = $('<div></div>');
    $textAndPic.append("节点名称：<input type=text id=node_name value='"+nodeName+"'>");
    
    BootstrapDialog.show({
        title: '节点属性',
        message: $textAndPic,
        buttons: [{
            label: '确定',
            action: function(dialogRef){
				var nameLine2 = "";
				var name = jQuery("#node_name").val();

				var nameArry = splitNameToArray(name);
				cellObj.attributes.attrs[".name"].text = nameArry[0];
				cellObj.attributes.attrs[".name_line2"].text = nameArry[1];
				if (cellObj.attributes.attrs[".name_line3"]) {
					cellObj.attributes.attrs[".name_line3"].text = nameArry[2];	
				}
				
				debugger;
				if (modelType == "org.Member") {
					resetCellHeight(nameArry, cellObj);				
				}
				
				cellObj.findView(paper).render();
				
				//处理关联线的刷新，避免线没对齐到点上 
				var opt = {deep : true};
				var relLinks = graph.getConnectedLinks(cellObj, opt);
				jQuery.each(relLinks, function(index, item){
					item.findView(paper).render();		 
				});		 	
				
		
				//这块的原因是 上面重新render之后， 拖动节点， 线就乱了，所以暂时先重新load
				var jsonObj =  graph.toJSON();
				graph.clear();
				graph.fromJSON(jsonObj);				
				
				
			    var extObj = {};
			    
			    setNodeInfo(cellObjId, extObj);            	

                dialogRef.close();
            }
        }, {
            label: '取消',
            action: function(dialogRef){
                dialogRef.close();
            }
        }]
    });
}


function showLinkView(linkObj) {
	var linkObjId = linkObj.id;
	var linkLabel = linkObj.get("labels")[0].attrs.text.text;

	var canBackChecked = "checked";
	if (linkObj.attributes.type != "fsa.Arrow") {
		canBackChecked = "";
	}

    var $textAndPic = $('<div></div>');
    $textAndPic.append("连线名称：<input type=text id=link_name value='"+linkLabel+"'>");
    $textAndPic.append("<br><br>");
    $textAndPic.append("可返回：<input type='checkbox' id='link_can_back' value='1' "+canBackChecked+">  ");
    
    BootstrapDialog.show({
        title: '连线属性',
        message: $textAndPic,
        buttons: [{
            label: '确定',
            action: function(dialogRef){       
				 //修改线上的信息 ， 线条件的名称
				 var linkId = linkObj.id;
				 linkObj.attributes.labels[0].attrs.text.text = jQuery("#link_name").val();
				 var vertices = linkObj.attributes.vertices;
				 linkObj.remove();
				 
				 var linkName = jQuery("#link_name").val();
				 if ($('#link_can_back').is(':checked')) {
					 link(linkObj.attributes.source, linkObj.attributes.target, linkName, vertices, linkId)
				 } else {
					 linkNoBack(linkObj.attributes.source, linkObj.attributes.target, linkName, vertices, linkId)	 
				 }				
				
				
			    var extObj = {};
			    setLineInfo(linkObjId, extObj);    

                dialogRef.close();
            }
        }, {
            label: '取消',
            action: function(dialogRef){
                dialogRef.close();
            }
        }]
    });

}


/**
 * 删除节点
 * @param cellObj 节点对象
 */
function removeNode(cellObj) {
	if (!confirm("确定删除该节点?")) {
		return;
	}
	
	if (!cellObj) {
		var nodeId = jQuery("#node_id").val();
		cellObj = graph.getCell(nodeId);
	}
	
    //删除关联的线
    var opt = {deep : true};
    var relLinks = graph.getConnectedLinks(cellObj, opt);
    
	jQuery.each(relLinks, function(index, item){
		item.remove();
	});
    
    //删除节点
	cellObj.remove();		
}

/**
 * 删除线
 * @param cellObj
 */
function removeLink(cellObj) {
	if (!confirm("确定删除该线?")) {
		return;
	}
	
	cellObj.remove();
}

paper.on('cell:pointerup', 
    function(cellView, evt, x, y) { 
		if (cellView.sourceMagnet ) { //鼠标up的时候， 在两点之间划上一条线，  存在sourceMagnet
			var srcObjId = cellView.sourceMagnet.parentElement.parentElement.parentElement.getAttribute("model-id");
			
			var targetObjId = evt.toElement.parentElement.parentElement.parentElement.getAttribute("model-id");
			
			//删除直线
			var allLinks = graph.getLinks();
			
			var existLink = false;
			jQuery.each(allLinks, function(index, item){
				var isLinkType = false;
				var itemAttrType = item.attributes.type;
				if (itemAttrType == "fsa.Arrow" || itemAttrType == "fsa.ArrowNoback") {
					isLinkType = true;
				}
				if (!isLinkType) {  //不是线，则删除
					item.remove();
				}
				
				//是 fsa.Arrow 且  源点和目标点是一样的
				if (isLinkType && item.attributes.source.id == srcObjId && item.attributes.target.id == targetObjId) {
					existLink = true;
				}
			});
			
			if (!existLink) {
				//目标点在节点上				
				var srcModel = graph.getCell(srcObjId);
				
				var targetModel = graph.getCell(targetObjId);
				
				//创建曲线
				var newLinkId = randomStr();
				var vertices = new Array();
				if (srcObjId == targetObjId) {
					vertices.push({"x":srcModel.getBBox().x + 10, "y":srcModel.getBBox().y-40});
					vertices.push({"x":srcModel.getBBox().x + 40, "y":srcModel.getBBox().y - 40});
				}
				
				link(srcModel, targetModel, "", vertices, newLinkId);
				
			    var extObj = {};
			    setLineInfo(newLinkId, extObj);    
			}
		}
    }
);


/**
 * 
 * @param nodeId 节点ID
 */
function setNodeInfo(nodeId, extInfo) {
	var nodeObj = graph.getCell(nodeId);
	var baseObj = {};
	//baseObj.ndesc = nodeObj.attributes.attrs[".rank"].text;
	baseObj.nname = nodeObj.attributes.attrs[".name"].text;
	baseObj.id = nodeId;
	
	if (!extInfo) {
		extInfo = {};
	}
	
	var color = nodeObj.get("attrs")[".card"].fill;
	if (color == "#AAAFFF") {
		extInfo.startNode = "1";
	}
	
	//先判断是否已经有了
	jQuery.each(nodes, function(index, item){
		if (item && item.id == nodeId) { //已经存在了该ID的节点数据，则先删除
			nodes.splice(index, 1);
		}
	});
	
	nodes.push(jQuery.extend(baseObj, extInfo));  //节点的所有信息
}

/**
 * 
 * @param linkId 连线ID
 */
function setLineInfo(linkId, extInfo) {
	var linkObj = graph.getCell(linkId);
	var baseObj = {};
	
	baseObj.label = linkObj.attributes.labels[0].attrs.text.text;	
	baseObj.source = linkObj.get("source").id;
	baseObj.target = linkObj.get("target").id;
	baseObj.id = linkId;
	
	if (!extInfo) {
		extInfo = {};
	}
	
	//先判断是否已经有了
	jQuery.each(lines, function(index, item){
		if (item && item.id == linkId) { //已经存在了该ID的连线数据，则先删除
			lines.splice(index, 1);
		}
	});
	
	lines.push(jQuery.extend(baseObj, extInfo));  //节点的所有信息
}

/**
var bart = member(300, 70, 'CEO', 'Bart Simpson', 'male.png', '#30d0c6');
var homer = member(90, 200, 'VP Marketing', 'Homer Simpson', 'male.png', '#7c68fd', '#f1f1f1');
var marge = member(300, 200, 'VP Sales', 'Marge Simpson', 'female.png', '#7c68fd', '#f1f1f1');
var lisa = member(500, 200, 'VP Production' , 'Lisa Simpson', 'female.png', '#7c68fd', '#f1f1f1');
var maggie = member(400, 350, 'Manager', 'Maggie Simpson', 'female.png', '#feb563');
var lenny = member(190, 350, 'Manager', 'Lenny Leonard', 'male.png', '#feb563');
var carl = member(190, 500, 'Manager', 'Carl Carlson', 'male.png', '#feb563');


link(bart, marge, "link1");
link(bart, homer, "");
link(bart, lisa, "");
link(homer, lenny, "");
link(homer, carl, "");
link(marge, maggie, "");
*/

function randomStr() {
    return Math.random().toString(36).substr(2); // remove `0.`
};

/**
 * 初始化
 * @param wfDefObj
 */
function initWf(wfDefObj) {
	if (wfDefObj && wfDefObj.cells) {
		graph.fromJSON(wfDefObj);	
	} else { //新添加
		var firstNodeId = randomStr();
		var secondNodeId = randomStr();
		var thirdNodeId = randomStr();
		var firstLinkId = randomStr();
		var secondLinkId = randomStr();
		 
		var jsonGraphString = 
{"cells":[{"type":"org.START","size":{"width":50,"height":50},"position":{"x":52,"y":54},"angle":0,"id":"bxpnm52jnyw","z":1,"attrs":{".card":{"fill":"#7ff78d","stroke":"#333","stroke-width":"1"},".name":{"font-family":"Arial","font-size":13,"text":"起草","fill":"#09365d","letter-spacing":0},".name_line2":{"font-family":"Arial","font-size":13,"text":"","fill":"#09365d","letter-spacing":0},"image":{"xlink:href":"images/male.png","magnet":true,"opacity":0.7},".rank":{"text":"审核","fill":"#09365d","word-spacing":"-5px","letter-spacing":0}}},{"type":"org.GateWay","size":{"width":60,"height":60},"position":{"x":418,"y":26},"angle":0,"id":"xnnozxcjb2","z":2,"attrs":{".card":{"fill":"#ffffff","stroke":"#333","stroke-width":"1"},".name":{"font-family":"Arial","font-size":13,"text":"网关","fill":"#09365d","letter-spacing":0},".rank":{"text":"审核","fill":"#09365d","word-spacing":"-5px","letter-spacing":0},".name_line2":{"text":"","fill":"#09365d","font-size":13,"font-family":"Arial","letter-spacing":0}}},{"type":"org.END","size":{"width":50,"height":50},"position":{"x":713,"y":247},"angle":0,"id":"fwqfqnias2","z":3,"attrs":{".card":{"fill":"#e89882","stroke":"#333","stroke-width":"3"},".name":{"font-family":"Arial","font-size":13,"text":"结束","fill":"#09365d","letter-spacing":0},".name_line2":{"font-family":"Arial","font-size":13,"text":"","fill":"#09365d","letter-spacing":0}}},{"type":"org.Member","size":{"width":110,"height":33},"position":{"x":145,"y":33},"angle":0,"id":"pdowlod9g7o","z":4,"attrs":{".card":{"fill":"#ffffff","stroke":"#333","stroke-width":"1"},"image":{"xlink:href":"images/male.png","magnet":true,"opacity":0.7},".rank":{"text":"审核","fill":"#09365d","word-spacing":"-5px","letter-spacing":0},".name":{"font-family":"Arial","font-size":13,"text":"审核节点","fill":"#09365d","letter-spacing":0},".name_line2":{"font-family":"Arial","font-size":13,"text":"","fill":"#09365d","letter-spacing":0}}},{"type":"fsa.Arrow","smooth":true,"source":{"id":"bxpnm52jnyw"},"target":{"id":"pdowlod9g7o"},"id":"h892kq2mkqa","labels":[{"position":0.5,"attrs":{"text":{"text":"","font-weight":"bold"}}}],"vertices":[],"z":5,"attrs":{}},{"type":"fsa.Arrow","smooth":true,"source":{"id":"pdowlod9g7o"},"target":{"id":"xnnozxcjb2"},"id":"ayr71a99z8j","labels":[{"position":0.5,"attrs":{"text":{"text":"","font-weight":"bold"}}}],"vertices":[],"z":6,"attrs":{}},{"type":"org.Member","size":{"width":110,"height":33},"position":{"x":362,"y":227},"angle":0,"id":"a2wn3w7gfvg","z":7,"attrs":{".card":{"fill":"#ffffff","stroke":"#333","stroke-width":"1"},"image":{"xlink:href":"images/male.png","magnet":true,"opacity":0.7},".rank":{"text":"审核","fill":"#09365d","word-spacing":"-5px","letter-spacing":0},".name":{"font-family":"Arial","font-size":13,"text":"审核节点","fill":"#09365d","letter-spacing":0},".name_line2":{"font-family":"Arial","font-size":13,"text":"","fill":"#09365d","letter-spacing":0}}},{"type":"org.Member","size":{"width":110,"height":45},"position":{"x":619,"y":39},"angle":0,"id":"ebr2ziksj8r","z":9,"attrs":{".card":{"fill":"#ffffff","stroke":"#333","stroke-width":"1"},"image":{"xlink:href":"images/male.png","magnet":true,"opacity":0.7},".rank":{"text":"审核","fill":"#09365d","word-spacing":"-5px","letter-spacing":0},".name":{"font-family":"Arial","font-size":13,"text":"审核节点很","fill":"#09365d","letter-spacing":0},".name_line2":{"font-family":"Arial","font-size":13,"text":"长的一个名字叫什么","fill":"#09365d","letter-spacing":0}}},{"type":"fsa.Arrow","smooth":true,"source":{"id":"xnnozxcjb2"},"target":{"id":"ebr2ziksj8r"},"id":"biepjz06sj6","labels":[{"position":0.5,"attrs":{"text":{"text":"","font-weight":"bold"}}}],"vertices":[],"z":10,"attrs":{}},{"type":"org.Member","size":{"width":110,"height":33},"position":{"x":670,"y":126},"angle":0,"id":"q20jykeqqzk","z":13,"attrs":{".card":{"fill":"#ffffff","stroke":"#333","stroke-width":"1"},"image":{"xlink:href":"images/male.png","magnet":true,"opacity":0.7},".rank":{"text":"审核","fill":"#09365d","word-spacing":"-5px","letter-spacing":0},".name":{"font-family":"Arial","font-size":13,"text":"审核节点","fill":"#09365d","letter-spacing":0},".name_line2":{"font-family":"Arial","font-size":13,"text":"","fill":"#09365d","letter-spacing":0}}},{"type":"fsa.Arrow","smooth":true,"source":{"id":"ebr2ziksj8r"},"target":{"id":"q20jykeqqzk"},"id":"xwku8mzcoxp","labels":[{"position":0.5,"attrs":{"text":{"text":"","font-weight":"bold"}}}],"vertices":[],"z":14,"attrs":{}},{"type":"fsa.Arrow","smooth":true,"source":{"id":"q20jykeqqzk"},"target":{"id":"fwqfqnias2"},"id":"am1m6c5a5to","labels":[{"position":0.5,"attrs":{"text":{"text":"","font-weight":"bold"}}}],"vertices":[],"z":15,"attrs":{}},{"type":"fsa.ArrowNoback","smooth":true,"source":{"id":"a2wn3w7gfvg"},"target":{"id":"fwqfqnias2"},"id":"04fsy6spbqd2","labels":[{"position":0.5,"attrs":{"text":{"text":"","font-weight":"bold"}}}],"vertices":[],"z":17,"attrs":{}},{"type":"fsa.ArrowNoback","smooth":true,"source":{"id":"xnnozxcjb2"},"target":{"id":"a2wn3w7gfvg"},"id":"td2y07ipyd8","labels":[{"position":0.5,"attrs":{"text":{"text":"测试","font-weight":"bold"}}}],"vertices":[],"z":18,"attrs":{".connection":{"stroke-dasharray":"4 2"}}},{"type":"fsa.ArrowNoback","smooth":true,"source":{"id":"pdowlod9g7o"},"target":{"id":"pdowlod9g7o"},"id":"t2imtniujr","labels":[{"position":0.5,"attrs":{"text":{"text":"","font-weight":"bold"}}}],"vertices":[{"x":170,"y":120},{"x":216,"y":126}],"z":19,"attrs":{}}]};
	//{"cells":[{"type":"org.START","size":{"width":50,"height":50},"position":{"x":52,"y":54},"angle":0,"id":"bxpnm52jnyw","z":1,"attrs":{".card":{"fill":"#7ff78d","stroke":"#333","stroke-width":"1"},".name":{"font-family":"Arial","font-size":13,"text":"起草","fill":"#09365d","letter-spacing":0},".name_line2":{"font-family":"Arial","font-size":13,"text":"","fill":"#09365d","letter-spacing":0},"image":{"xlink:href":"images/male.png","magnet":true,"opacity":0.7},".rank":{"text":"审核","fill":"#09365d","word-spacing":"-5px","letter-spacing":0}}},{"type":"org.GateWay","size":{"width":60,"height":60},"position":{"x":418,"y":26},"angle":0,"id":"xnnozxcjb2","z":2,"attrs":{".card":{"fill":"#ffffff","stroke":"#333","stroke-width":"1"},".name":{"font-family":"Arial","font-size":13,"text":"网关","fill":"#09365d","letter-spacing":0},".rank":{"text":"审核","fill":"#09365d","word-spacing":"-5px","letter-spacing":0},".name_line2":{"text":"","fill":"#09365d","font-size":13,"font-family":"Arial","letter-spacing":0}}},{"type":"org.END","size":{"width":50,"height":50},"position":{"x":713,"y":247},"angle":0,"id":"fwqfqnias2","z":3,"attrs":{".card":{"fill":"#e89882","stroke":"#333","stroke-width":"3"},".name":{"font-family":"Arial","font-size":13,"text":"结束","fill":"#09365d","letter-spacing":0},".name_line2":{"font-family":"Arial","font-size":13,"text":"","fill":"#09365d","letter-spacing":0}}},{"type":"org.Member","size":{"width":110,"height":33},"position":{"x":145,"y":33},"angle":0,"id":"pdowlod9g7o","z":4,"attrs":{".card":{"fill":"#ffffff","stroke":"#333","stroke-width":"1"},"image":{"xlink:href":"images/male.png","magnet":true,"opacity":0.7},".rank":{"text":"审核","fill":"#09365d","word-spacing":"-5px","letter-spacing":0},".name":{"font-family":"Arial","font-size":13,"text":"审核节点","fill":"#09365d","letter-spacing":0},".name_line2":{"font-family":"Arial","font-size":13,"text":"","fill":"#09365d","letter-spacing":0}}},{"type":"fsa.Arrow","smooth":true,"source":{"id":"bxpnm52jnyw"},"target":{"id":"pdowlod9g7o"},"id":"h892kq2mkqa","labels":[{"position":0.5,"attrs":{"text":{"text":"","font-weight":"bold"}}}],"vertices":[],"z":5,"attrs":{}},{"type":"fsa.Arrow","smooth":true,"source":{"id":"pdowlod9g7o"},"target":{"id":"xnnozxcjb2"},"id":"ayr71a99z8j","labels":[{"position":0.5,"attrs":{"text":{"text":"","font-weight":"bold"}}}],"vertices":[],"z":6,"attrs":{}},{"type":"org.Member","size":{"width":110,"height":33},"position":{"x":362,"y":227},"angle":0,"id":"a2wn3w7gfvg","z":7,"attrs":{".card":{"fill":"#ffffff","stroke":"#333","stroke-width":"1"},"image":{"xlink:href":"images/male.png","magnet":true,"opacity":0.7},".rank":{"text":"审核","fill":"#09365d","word-spacing":"-5px","letter-spacing":0},".name":{"font-family":"Arial","font-size":13,"text":"审核节点","fill":"#09365d","letter-spacing":0},".name_line2":{"font-family":"Arial","font-size":13,"text":"","fill":"#09365d","letter-spacing":0}}},{"type":"org.Member","size":{"width":110,"height":33},"position":{"x":619,"y":39},"angle":0,"id":"ebr2ziksj8r","z":9,"attrs":{".card":{"fill":"#ffffff","stroke":"#333","stroke-width":"1"},"image":{"xlink:href":"images/male.png","magnet":true,"opacity":0.7},".rank":{"text":"审核","fill":"#09365d","word-spacing":"-5px","letter-spacing":0},".name":{"font-family":"Arial","font-size":13,"text":"审核节点","fill":"#09365d","letter-spacing":0},".name_line2":{"font-family":"Arial","font-size":13,"text":"","fill":"#09365d","letter-spacing":0}}},{"type":"fsa.Arrow","smooth":true,"source":{"id":"xnnozxcjb2"},"target":{"id":"ebr2ziksj8r"},"id":"biepjz06sj6","labels":[{"position":0.5,"attrs":{"text":{"text":"","font-weight":"bold"}}}],"vertices":[],"z":10,"attrs":{}},{"type":"org.Member","size":{"width":110,"height":33},"position":{"x":670,"y":126},"angle":0,"id":"q20jykeqqzk","z":13,"attrs":{".card":{"fill":"#ffffff","stroke":"#333","stroke-width":"1"},"image":{"xlink:href":"images/male.png","magnet":true,"opacity":0.7},".rank":{"text":"审核","fill":"#09365d","word-spacing":"-5px","letter-spacing":0},".name":{"font-family":"Arial","font-size":13,"text":"审核节点","fill":"#09365d","letter-spacing":0},".name_line2":{"font-family":"Arial","font-size":13,"text":"","fill":"#09365d","letter-spacing":0}}},{"type":"fsa.Arrow","smooth":true,"source":{"id":"ebr2ziksj8r"},"target":{"id":"q20jykeqqzk"},"id":"xwku8mzcoxp","labels":[{"position":0.5,"attrs":{"text":{"text":"","font-weight":"bold"}}}],"vertices":[],"z":14,"attrs":{}},{"type":"fsa.Arrow","smooth":true,"source":{"id":"q20jykeqqzk"},"target":{"id":"fwqfqnias2"},"id":"am1m6c5a5to","labels":[{"position":0.5,"attrs":{"text":{"text":"","font-weight":"bold"}}}],"vertices":[],"z":15,"attrs":{}},{"type":"fsa.ArrowNoback","smooth":true,"source":{"id":"a2wn3w7gfvg"},"target":{"id":"fwqfqnias2"},"id":"04fsy6spbqd2","labels":[{"position":0.5,"attrs":{"text":{"text":"","font-weight":"bold"}}}],"vertices":[],"z":17,"attrs":{}},{"type":"fsa.ArrowNoback","smooth":true,"source":{"id":"xnnozxcjb2"},"target":{"id":"a2wn3w7gfvg"},"id":"td2y07ipyd8","labels":[{"position":0.5,"attrs":{"text":{"text":"测试","font-weight":"bold"}}}],"vertices":[],"z":18,"attrs":{".connection":{"stroke-dasharray":"4 2"}}},{"type":"fsa.ArrowNoback","smooth":true,"source":{"id":"pdowlod9g7o"},"target":{"id":"pdowlod9g7o"},"id":"t2imtniujr","labels":[{"position":0.5,"attrs":{"text":{"text":"","font-weight":"bold"}}}],"vertices":[{"x":170,"y":120},{"x":216,"y":126}],"z":19,"attrs":{}}]};
		
		
		graph.fromJSON(jsonGraphString);
		
		//初始化节点
		jQuery.each(graph.getElements(), function(index, item){
			setNodeInfo(item.get("id"));
		});
		
		//初始化连线
		jQuery.each(graph.getLinks(), function(index, item){
			setLineInfo(item.get("id"));
		});
	}
}


function addNode(x, y ){
	var newNodeId = randomStr();

	var nodeAttr = getNodePubAttr(globleTempNodeType);
	if (globleTempNodeType == "gateway") {
		gateWayObj(newNodeId, x, y, '审核', nodeAttr.name, 'male.png', nodeAttr.bgcolor, '#09365d');	
	} else if (globleTempNodeType == "start") {
		startObj(newNodeId, x, y, '审核', nodeAttr.name, 'male.png', nodeAttr.bgcolor, '#09365d');	
	} else if (globleTempNodeType == "end") {
		endObj(newNodeId, x, y, '审核', nodeAttr.name, 'male.png', nodeAttr.bgcolor, '#09365d');	
	} else {
		member(newNodeId, x, y, '审核', nodeAttr.name, 'male.png', nodeAttr.bgcolor, '#09365d');		
	}
	
	
    var extObj = {};
    setNodeInfo(newNodeId, extObj);	
}


var gateWayObj = function(id, x, y, rank, name, image, background, textColor) {

    textColor = textColor || "#000";

    var nameLine2 = "";
    if (name.length > 5) {
    	nameLine2 = name.substring(5);
    	name = name.substring(0, 5);
    }	
	
    var cell = new joint.shapes.org.GateWay({
        position: { x: x, y: y },
        id: id,
        attrs: {
            '.card': { fill: background, stroke: '#333', "stroke-width":"1"},
            '.rank': { text: rank, fill: textColor, 'word-spacing': '-5px', 'letter-spacing': 0},
            '.name': { text: name, fill: textColor, 'font-size': 13, 'font-family': 'Arial', 'letter-spacing': 0 },
			'.name_line2': { text: nameLine2, fill: textColor, 'font-size': 13, 'font-family': 'Arial', 'letter-spacing': 0 }
        }
    });
	
    if (nameLine2.length > 0) {
    	cell.attributes.size.height = 45	
    }	
	
    graph.addCell(cell);
    return cell;
};



var startObj = function(id, x, y, rank, name, image, background, textColor) {

    textColor = textColor || "#000";

    var nameLine2 = "";
    if (name.length > 5) {
    	nameLine2 = name.substring(5);
    	name = name.substring(0, 5);
    }	
	
    var cell = new joint.shapes.org.START({
        position: { x: x, y: y },
        id: id,
        attrs: {
            '.card': { fill: background, stroke: '#333', "stroke-width":"1"},
              image: { 'xlink:href': 'images/'+ image, "magnet":true, opacity: 0.7 },
            '.rank': { text: rank, fill: textColor, 'word-spacing': '-5px', 'letter-spacing': 0},
            '.name': { text: name, fill: textColor, 'font-size': 13, 'font-family': 'Arial', 'letter-spacing': 0 },
			'.name_line2': { text: nameLine2, fill: textColor, 'font-size': 13, 'font-family': 'Arial', 'letter-spacing': 0 }
        }
    });
	
    if (nameLine2.length > 0) {
    	cell.attributes.size.height = 45	
    }	
	
    graph.addCell(cell);
    return cell;
};




var endObj = function(id, x, y, rank, name, image, background, textColor) {

    textColor = textColor || "#000";

    var nameLine2 = "";
    if (name.length > 5) {
    	nameLine2 = name.substring(5);
    	name = name.substring(0, 5);
    }	
	
    var cell = new joint.shapes.org.END({
        position: { x: x, y: y },
        id: id,
        attrs: {
            '.card': { fill: background, stroke: '#333', "stroke-width":"3"},
            '.name': { text: name, fill: textColor, 'font-size': 13, 'font-family': 'Arial', 'letter-spacing': 0 },
			'.name_line2': { text: nameLine2, fill: textColor, 'font-size': 13, 'font-family': 'Arial', 'letter-spacing': 0 }
        }
    });
	
    if (nameLine2.length > 0) {
    	cell.attributes.size.height = 45	
    }	
	
    graph.addCell(cell);
    return cell;
};

var getNodePubAttr = function(nodeType) {
	var nodeAttr = {};
	if (nodeType == "approve") {
		nodeAttr.name = "审核节点";
		nodeAttr.bgcolor = "#ffffff";
	} else if (nodeType == "draft") {
		nodeAttr.name = "起草";
		nodeAttr.bgcolor = "#7ff78d";
	} else if (nodeType == "finish") {
		nodeAttr.name = "办结";
		nodeAttr.bgcolor = "#e89882";
	} else if (nodeType == "print") {
		nodeAttr.name = "文印";
		nodeAttr.bgcolor = "#ffffff";
	} else if (nodeType == "distribute") {
		nodeAttr.name = "会签";
		nodeAttr.bgcolor = "#ffffff";
	} else if (nodeType == "gateway") {
		nodeAttr.name = "网关";
		nodeAttr.bgcolor = "#ffffff";
	} else if (nodeType == "start") {
		nodeAttr.name = "起草";
		nodeAttr.bgcolor = "#7ff78d";
	} else if (nodeType == "end") {
		nodeAttr.name = "结束";
		nodeAttr.bgcolor = "#e89882";
	}				 	

	return nodeAttr;
}

var createNode = function(event, nodeType) {
	event.stopPropagation();
	
	var nodeAttr = getNodePubAttr(nodeType);

	var tempClass = "temp-float-node";
	if (nodeType == "start" || nodeType == "end") {
		tempClass = "temp-float-circle";
	} else if (nodeType == "gateway") {
		tempClass = "temp-float-gateway";
	}
	
	var tempNode = "<div id='tempFloatNode' class='"+tempClass+"' style='background-color:" + nodeAttr.bgcolor 
					+ "'>" + nodeAttr.name + "</div>";
	var tempNodeObj = $(tempNode).appendTo($("body"));

	tempNodeObj.css("left", event.clientX);
	tempNodeObj.css("top", event.clientY);

	globleTempNodeType = nodeType;
	globleTempNodeExistFlag = true;
}

var expData = function() {
	var wfdata = JSON.stringify(graph.toJSON());

	alert(wfdata);

	console.log(wfdata);
}

/**
 * @param cellObj 节点对象
 */
function refreshGraphWhenNodeChange(cellObj) {
	cellObj.findView(paper).render();
				
	//处理关联线的刷新，避免线没对齐到点上 
	var opt = {deep : true};
	var relLinks = graph.getConnectedLinks(cellObj, opt);
	jQuery.each(relLinks, function(index, item){
		item.findView(paper).render();		 
	});		 	
	

	//这块的原因是 上面重新render之后， 拖动节点， 线就乱了，所以暂时先重新load
	var jsonObj =  graph.toJSON();
	graph.clear();
	graph.fromJSON(jsonObj);	
}

/**
 * 处理选中元素的事件
 * @param event 事件
 */
function handleSelectCellEvent(event) {
	//取消所有的 轮廓虚框
	jQuery(".node-resize-outline").remove();
	//添加判断，如果点击的是节点类型，则添加调整大小
	var evtTargetObj = event.target;
	if (evtTargetObj.parentNode && evtTargetObj.parentNode.parentNode && 
		evtTargetObj.parentNode.parentNode.parentNode && 
		evtTargetObj.parentNode.parentNode.parentNode.hasAttribute("model-id")) {
		
		var modelId = evtTargetObj.parentNode.parentNode.parentNode.getAttribute("model-id");
		var dataType = evtTargetObj.parentNode.parentNode.parentNode.getAttribute("data-type");
		var cellObj = graph.getCell(modelId);
		var nodeWidth = cellObj.attributes.size.width;
		var nodeHeight = cellObj.attributes.size.height;
		var nodePX = cellObj.attributes.position.x;
		var nodePY = cellObj.attributes.position.y;
		var resizeX = nodePX, resizeY = nodePY;  //默认审批的矩形
		if (dataType == "org.START" || dataType == "org.END") { //圆类型
			resizeX = nodePX - (nodeWidth/2);
			resizeY = nodePY - (nodeHeight/2);
		} else if (dataType == "org.GateWay") { //网关
			resizeX = nodePX - (nodeWidth/2);
			resizeY = nodePY;
		}
		//在节点的位置画一个轮廓虚框
		var resizeOutlineObj = jQuery("<div class='node-resize-outline'></div>");
		resizeOutlineObj.appendTo($("#paper"));
		resizeOutlineObj.css("width", nodeWidth);
		resizeOutlineObj.css("height", nodeHeight)
		resizeOutlineObj.css("left", resizeX);
		resizeOutlineObj.css("top", resizeY);

	    resizeOutlineObj.resizable({
	      helper: "ui-resizable-helper"
	    });
		resizeOutlineObj.bind('resizestop', function(event, ui) {
			cellObj.attributes.size.width = ui.size.width;
			cellObj.attributes.size.height = ui.size.height;

			refreshGraphWhenNodeChange(cellObj);
			jQuery(".node-resize-outline").remove();
		});  

		resizeOutlineObj.bind("click", function(event){
			resizeOutlineObj.css("pointer-events", "none !important");
		});
	}
}


$(document).ready(function() {
	initWf();

	jQuery("body").bind("click", function(event) {
		//选中元素的事件
		handleSelectCellEvent(event);

		if (event.target.type == "button") {
			return;		
		}		
		if (jQuery("#tempFloatNode").length != 1) {
			return;
		}

		globleTempNodeExistFlag = false;
		
		if (globleTempNodeType == "start" || globleTempNodeType == "end") {
			addNode(event.clientX + 20, event.clientY - 20);
		} else if (globleTempNodeType == "gateway") {
			addNode(event.clientX + 20, event.clientY - 40);
		} else {
			addNode(event.clientX, event.clientY - 40);
		}
		
		jQuery("#tempFloatNode").remove();			
	});	
});




var globleTempNodeExistFlag = false;
var globleTempNodeType = "approve";
document.onmousemove = function(event) {
	if (jQuery("#tempFloatNode").length == 1 && globleTempNodeExistFlag) {
		jQuery("#tempFloatNode").css("left", event.clientX);
		jQuery("#tempFloatNode").css("top", event.clientY);		
	} 
}







var showHelpMsg = function(event) {
	var message = "单击左侧蓝色按钮则会出现小节点，移动鼠标放到希望放的地方单击就放下了，还可拖动节点调整位置。<br>"+
	              "鼠标晃动到节点上的小人上面时，会变成十字形状，点击拉到需要流向的节点，单击，就有线啦。<br>"+
	              "双击节点即可修改节点属性（暂时只可修改节点名称）。"+
	              "鼠标晃到节点或线上时出现的红色的叉，可删除";

    BootstrapDialog.show({
        title: '帮助信息',
        message: message,
        buttons: [{
            label: '确定',
            action: function(dialog) {
                dialog.close();
            }
        }]
    });	
}

paper.on('cell:mouseover',function (cellView, evt) {
	var cellObj = cellView.model;
	
	var modelType = cellObj.get("type");
	
	if (modelType == "org.Member" || modelType == "org.START" || modelType == "org.END" || modelType == "org.GateWay") {
		jQuery("[model-id='" + cellObj.id + "']").find(".tool-remove").show()
	} 
	
	evt.stopPropagation();
});

paper.on('cell:mouseout',function (cellView, evt) {
	var cellObj = cellView.model;
	var modelType = cellObj.get("type");
	
	if (modelType == "org.Member" || modelType == "org.START" || modelType == "org.END" || modelType == "org.GateWay") {
		jQuery("[model-id='" + cellObj.id + "']").find(".tool-remove").hide()
	} 
	evt.stopPropagation();
});

paper.on('cell:pointermove',function (cellView, evt, x, y) {
	console.log("x: " + x + " y: " + y);
	var cellObj = cellView.model;

    var opt = {deep : true};
    var relLinks = graph.getConnectedLinks(cellObj, opt);
    
	jQuery.each(relLinks, function(index, linkObj){
		//线的source和target都是自己， 则重新画线
		if (cellObj.id == linkObj.attributes.source.id && cellObj.id == linkObj.attributes.target.id) {
			var linkId = linkObj.id;
			linkObj.remove();

			var vertices = new Array();
			vertices.push({"x":cellObj.getBBox().x + 10, "y":cellObj.getBBox().y-40});
			vertices.push({"x":cellObj.getBBox().x + 40, "y":cellObj.getBBox().y - 40});

			var linkName = linkObj.attributes.labels[0].attrs.text.text;
			if (linkObj.attributes.type == "fsa.Arrow") { //可返回
				link(cellObj, cellObj, linkName, vertices, linkId)
			} else {
				linkNoBack(cellObj, cellObj, linkName, vertices, linkId)	 
			}		
		}
	});	
});
	
	